package com.haoma.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haoma.dto.PhotoDto;
import com.haoma.entity.Photo;
import com.haoma.entity.PhotoCategory;
import com.haoma.entity.PhotoCategoryRelation;
import com.haoma.mapper.PhotoCategoryMapper;
import com.haoma.mapper.PhotoCategoryRelationMapper;
import com.haoma.mapper.PhotoMapper;
import com.haoma.minio.MinIOConfig;
import com.haoma.minio.MinIOConfigProperties;
import com.haoma.service.PhotoService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * Description: 相册相关接口
 */
@Service
public class PhotoServiceImpl extends ServiceImpl<PhotoMapper, Photo> implements PhotoService {


    @Autowired
    private MinIOConfig minIOConfig;

    @Autowired
    private MinIOConfigProperties minIOConfigProperties;

    @Autowired
    private PhotoCategoryRelationMapper photoCategoryRelationMapper;

    @Autowired
    private PhotoMapper photoMapper;

    @Autowired
    private PhotoCategoryMapper photoCategoryMapper;

    /**
     * 相册图片上传
     *
     * @param id
     * @param multipartFile
     */
    public void photoUpload(Integer id, MultipartFile multipartFile) {
        try {
            // 连接客户端
            MinioClient minioClient = minIOConfig.buildMinioClient();
            // 判断桶是否存在
            boolean isBucket = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minIOConfigProperties.getBucket()).build());
            if (!isBucket) {
                // 不存在创建一个
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minIOConfigProperties.getBucket()).build());
            } else {
                // 提示程序员存在
                System.out.println("Bucket 'test' already exists.");
            }
            // 设置存储路径
            // 当天作为目录
            String date = DateUtil.format(new Date(), "yyyyMMdd");
            // 唯一id作为图片路径
            String uuid = UUID.randomUUID().toString().replace("-", "");
            // 组合＋业务
            String fileName = "admin-photo" + "/" + date + "/" + uuid + multipartFile.getOriginalFilename();
            System.out.println(fileName);

            // 构建上传参数
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(minIOConfigProperties.getBucket())
                    .stream(multipartFile.getInputStream(), multipartFile.getSize(), -1)
                    .object(fileName)
                    .build();
            // 上传
            minioClient.putObject(putObjectArgs);
            String addressUrl = minIOConfigProperties.getReadPath() + "/" + minIOConfigProperties.getBucket() + "/" + fileName;
            if (id != null) {
                // 上传到数据库中
                Photo photo = new Photo();
                photo.setPhotoUrl(addressUrl);
                photo.setState(2);
                photoMapper.insert(photo);
                // 根据分类id插入到数据库中
                // 插入到第三方关系表中
                PhotoCategoryRelation photoCategoryRelation = new PhotoCategoryRelation();
                photoCategoryRelation.setPhotoId(photo.getId());
                photoCategoryRelation.setCategoryId(id);
                photoCategoryRelationMapper.insert(photoCategoryRelation);
                // 更新相册数量
                LambdaQueryWrapper<PhotoCategory> photoCategoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
                photoCategoryLambdaQueryWrapper.eq(PhotoCategory::getId, id);
                // 先查询
                PhotoCategory photoCategoryDb = photoCategoryMapper.selectOne(photoCategoryLambdaQueryWrapper);
                // 修改数量
                photoCategoryDb.setCount(photoCategoryDb.getCount() + 1);
                // 修改
                photoCategoryMapper.update(photoCategoryDb, photoCategoryLambdaQueryWrapper);
                if (id != 7) {
                    LambdaQueryWrapper<PhotoCategory> photoCategoryLambdaQuery= new LambdaQueryWrapper<>();
                    photoCategoryLambdaQuery.eq(PhotoCategory::getId, 1);
                    // 先查询
                    PhotoCategory photoCategoryAll = photoCategoryMapper.selectOne(photoCategoryLambdaQuery);
                    // 修改数量
                    photoCategoryAll.setCount(photoCategoryAll.getCount() + 1);
                    // 修改
                    photoCategoryMapper.update(photoCategoryAll, photoCategoryLambdaQuery);
                }

            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据分类id获取到相册
     *
     * @param state
     * @param id
     * @return
     */
    public List<String> getPhotoById(Integer state, Integer id) {
        // 如果为全部则需要展示全部的照片
        if (id == 1) {
            // 查询全部相册
            List<Photo> list = list();
            // 遍历映射到
            List<String> allList = list.stream()
                    .filter(photo -> Objects.equals(photo.getState(), state))
                    // 根据id倒序排序也就是新创建的先展示
                    .sorted(Comparator.comparing(Photo::getId).reversed())
                    // 获取到图片路径就可
                    .map(Photo::getPhotoUrl)
                    // 转换为集合
                    .toList();
            // 返回全部的图片集合
            return allList;
        }
        // 根据分类id查询关系表
        LambdaQueryWrapper<PhotoCategoryRelation> photoCategoryRelationLambdaQueryWrapper = new LambdaQueryWrapper<>();
        photoCategoryRelationLambdaQueryWrapper.eq(PhotoCategoryRelation::getCategoryId, id);
        photoCategoryRelationLambdaQueryWrapper.orderByDesc(PhotoCategoryRelation::getCreateTime);
        List<PhotoCategoryRelation> photoCategoryRelations = photoCategoryRelationMapper.selectList(photoCategoryRelationLambdaQueryWrapper);
        // 校验
        if (CollectionUtils.isEmpty(photoCategoryRelations)) {
            // 为空返回空集合
            return new ArrayList<>();
        }
        // 获取到所有的图片id
        List<Integer> photoIdList = photoCategoryRelations
                .stream()
                .map(PhotoCategoryRelation::getPhotoId)
                .toList();
        // 查询图片表
        List<Photo> photoList = photoMapper.selectBatchIds(photoIdList);
        // 校验
        if (CollectionUtils.isEmpty(photoList)) {
            // 为空返回空集合
            return new ArrayList<>();
        }
        // 转换为String类型并排序
        List<String> list = photoList.stream()
                // 过滤到状态为2的相册
                .filter(photo -> Objects.equals(photo.getState(), state))
                // 然后将相册根据id排序
                .sorted(Comparator.comparing(Photo::getId).reversed())
                // 映射成相册路径
                .map(Photo::getPhotoUrl)
                // 转换为集合
                .toList();
        return list;
    }

    /**
     * 删除分类下的图片
     *
     * @param photoDto
     */
    public void delPhoto(PhotoDto photoDto) {
        // 先查询图片数据库
        LambdaQueryWrapper<Photo> photoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        photoLambdaQueryWrapper.eq(Photo::getPhotoUrl, photoDto.getPhotoUrl());
        Photo photo = photoMapper.selectOne(photoLambdaQueryWrapper);
        photo.setState(3);
        photoMapper.updateById(photo);

        // 从关系表中移除
        LambdaQueryWrapper<PhotoCategoryRelation> photoCategoryRelationLambdaQueryWrapper = new LambdaQueryWrapper<>();
        photoCategoryRelationLambdaQueryWrapper.eq(PhotoCategoryRelation::getPhotoId, photo.getId());
        // 先查询
        PhotoCategoryRelation photoCategoryRelation = photoCategoryRelationMapper.selectOne(photoCategoryRelationLambdaQueryWrapper);

        // 查询相册分类表将相册分类表的数量减一
        LambdaQueryWrapper<PhotoCategory> photoCategoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        photoCategoryLambdaQueryWrapper.eq(PhotoCategory::getId, photoCategoryRelation.getCategoryId());
        PhotoCategory photoCategory = photoCategoryMapper.selectOne(photoCategoryLambdaQueryWrapper);
        // 将数量减一
        photoCategory.setCount(photoCategory.getCount() - 1);
        if(photoCategoryRelation.getCategoryId() != 7) {
            LambdaQueryWrapper<PhotoCategory> photoCategoryLambdaQuery = new LambdaQueryWrapper<>();
            photoCategoryLambdaQuery.eq(PhotoCategory::getId, 1);
            // 先查询
            PhotoCategory photoCategoryAll = photoCategoryMapper.selectOne(photoCategoryLambdaQuery);
            // 修改数量
            photoCategoryAll.setCount(photoCategoryAll.getCount() + 1);
            // 修改
            photoCategoryMapper.update(photoCategoryAll, photoCategoryLambdaQuery);
        }
        // 更新
        photoCategoryMapper.update(photoCategory, photoCategoryLambdaQueryWrapper);
    }

    /**
     * 隐藏图片
     *
     * @param state
     * @param photoDto
     */
    public void concealPhoto(Integer state, PhotoDto photoDto) {
        LambdaQueryWrapper<Photo> photoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        photoLambdaQueryWrapper.eq(Photo::getPhotoUrl, photoDto.getPhotoUrl());
        Photo photo = photoMapper.selectOne(photoLambdaQueryWrapper);
        photo.setState(state);
        photoMapper.updateById(photo);
    }

    /**
     * 获取所有的视频
     *
     * @param state
     * @return
     */
    public List<String> getVideoList(Integer state) {
        // 查询关系表中为7
        LambdaQueryWrapper<PhotoCategoryRelation> photoCategoryRelationLambdaQueryWrapper = new LambdaQueryWrapper<>();
        photoCategoryRelationLambdaQueryWrapper.eq(PhotoCategoryRelation::getCategoryId, 7);
        List<PhotoCategoryRelation> photoCategoryRelations = photoCategoryRelationMapper.selectList(photoCategoryRelationLambdaQueryWrapper);

        // 获取到所有的视频id
        List<Integer> idList = photoCategoryRelations.stream()
                .map(PhotoCategoryRelation::getPhotoId).toList();

        // 根据id集合查询相册表
        List<Photo> photoListDb = photoMapper.selectBatchIds(idList);

        // 遍历状态为显示的
        List<String> list = photoListDb.stream()
                .filter(item -> item.getState() == state)
                .map(Photo::getPhotoUrl)
                .toList();


        // 将视频路径返回
        return list;
    }


}
